#! /usr/bin/env bash
# icecc -- A simple distributed compiler system
#
# Copyright (C) 2004 by the Icecream Authors
# GPL

# Modified by: Ragner Magalhaes <ragner.magalhaes@gmail.com>
# Description: Creates a icecc tarball suitable for MADDE compilation

target_files=

is_darwin=0
if test `uname` = Darwin; then
  is_darwin=1
fi

is_contained ()
{
  case " $target_files " in
    *" $1 "* ) return 0 ;;
    *"=$1 "* ) return 0;;
    * ) return 1 ;;
  esac
}

add_file ()
{
  local name="$1"
  local path="$1";
  if test -n "$2"; then
    name="$2"
  fi
  test -z "$name" && return
  # ls -H isn't really the same as readlink, but
  # readlink is not portable enough. 
  path=`ls -H $path`
  toadd="$name=$path"
  if test "$name" = "$path"; then
    toadd=$path
  fi
  is_contained "$toadd" && return
  echo "adding file $toadd"
  target_files="$target_files $toadd"
  if test -x "$path"; then
    # Only call ldd when it makes sense
    if file -L "$path" | grep 'ELF' > /dev/null 2>&1; then
	if ! file -L "$path" | grep 'static' > /dev/null 2>&1; then
	   # ldd now outputs ld as /lib/ld-linux.so.xx on current nptl based glibc
		# this regexp parse the outputs like:
		# ldd /usr/bin/gcc
		#         linux-gate.so.1 =>  (0xffffe000)
		#         libc.so.6 => /lib/tls/libc.so.6 (0xb7e81000)
		#         /lib/ld-linux.so.2 (0xb7fe8000)
		# covering both situations ( with => and without )
           for lib in `ldd "$path" | sed -n 's,^[^/]*\(/[^ ]*\).*,\1,p'`; do
	      test -f "$lib" || continue
	      # Check wether the same library also exists in the parent directory,
	      # and prefer that on the assumption that it is a more generic one.
	      local baselib=`echo "$lib" | sed 's,\(/[^/]*\)/.*\(/[^/]*\)$,\1\2,'`
	      test -f "$baselib" && lib=$baselib
              add_file "$lib"
           done
        fi
    elif test "$is_darwin" = 1; then
          for lib in `otool -L "$path" | sed -n 's,^[^/]*\(/[^ ]*\).*,\1,p'`; do
	    test -f "$lib" || continue
	    # Check wether the same library also exists in the parent directory,
	    # and prefer that on the assumption that it is a more generic one.
	    local baselib=`echo "$lib" | sed 's,\(/[^/]*\)/.*\(/[^/]*\)$,\1\2,'`
	    test -f "$baselib" && lib=$baselib
            add_file "$lib"
         done
    fi
  fi
}

# backward compat
if test "$1" = "--respect-path"; then
  shift
fi

added_gcc=$1
shift
added_gxx=$1

if test -z "$added_gcc" || test -z "$added_gxx"; then
	echo "usage: $0 <gcc_path> <g++_path>"
	exit 1
fi
	
if ! test -x "$added_gcc" ; then
  echo "'$added_gcc' is no executable."
  exit 1
fi

if ! test -x "$added_gxx" ; then
  echo "'$added_gcc' is no executable."
  exit 1
fi

# cross compile

# gcc
custom_gcc=$(mktemp -t gccXXXX)

cat > "$custom_gcc.c" <<EOF
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{
	char *gcc = {"/usr/bin/arm-gcc"};
	char *specs = {"-specs=/etc/specs"};
	char *newenviron[] = { NULL };
	char **gcc_args = malloc(sizeof(char*) * (argc + 2));

	memcpy(gcc_args, argv, sizeof(char*) * argc);

	gcc_args[0] = gcc;

	if (argc > 1) {
		gcc_args[argc] = specs;
		gcc_args[argc + 1] = NULL;
	}

	execve(gcc, gcc_args, newenviron);

	return 1;
}
EOF

/usr/bin/gcc "$custom_gcc.c" -o $custom_gcc

# g++
custom_gxx=$(mktemp -t gxxXXXX)

cat > "$custom_gxx.c" <<EOF
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{
	char *gcc = {"/usr/bin/arm-g++"};
	char *specs = {"-specs=/etc/specs"};
	char *newenviron[] = { NULL };
	char **gcc_args = malloc(sizeof(char*) * (argc + 2));

	memcpy(gcc_args, argv, sizeof(char*) * argc);

	gcc_args[0] = gcc;

	if (argc > 1) {
		gcc_args[argc] = specs;
		gcc_args[argc + 1] = NULL;
	}

	execve(gcc, gcc_args, newenviron);

	return 1;
}
EOF

/usr/bin/gcc "$custom_gxx.c" -o $custom_gxx

add_file $custom_gcc /usr/bin/gcc
add_file $custom_gxx /usr/bin/g++

specs=$(mad query target-dir)/specs

if test -f "$specs"; then
   add_file "$specs" /etc/specs 
else
   echo "specs file not found."
   exit 1
fi

add_file $added_gcc /usr/bin/arm-gcc
add_file $added_gxx /usr/bin/arm-g++
gcc_as=$($added_gcc -print-prog-name=as)
if test "$gcc_as" = "as"; then
    add_file /usr/bin/as
else
    add_file "$gcc_as" /usr/bin/as
fi

if test "$is_darwin" = 1; then
    # add dynamic linker
    add_file /usr/lib/dyld
    real_file=`/usr/bin/gcc --version | head -n 1 2>&1 | cut -d" " -f1`
    add_file /usr/bin/$real_file
    real_file=`/usr/bin/g++ --version | head -n 1 2>&1 | cut -d" " -f1`
    add_file /usr/bin/$real_file
    real_file=`/usr/bin/as -micha -- < /dev/null 2>&1 | cut -d: -f1`
    add_file $real_file
fi


add_file `$added_gcc -print-prog-name=cc1` /usr/bin/cc1
add_file `$added_gxx -print-prog-name=cc1plus` /usr/bin/cc1plus
specfile=`$added_gcc -print-file-name=specs`
if test -n "$specfile" && test "$specfile" != "specs" && test -e "$specfile"; then
  add_file "$specfile"
fi

# for ldconfig -r to work, ld.so.conf must not contain relative paths
# in include directives. Make them absolute.
tmp_ld_so_conf=`mktemp /tmp/icecc_ld_so_confXXXXXX`
while read directive path; do
  if [ "$directive" = "include" -a "${path:0:1}" != "/" ]; then
    path="/etc/$path"
  fi
  echo "$directive $path"
done </etc/ld.so.conf >$tmp_ld_so_conf
echo "/lib" >> $tmp_ld_so_conf
add_file $tmp_ld_so_conf /etc/ld.so.conf

tempdir=`mktemp -d /tmp/iceccenvXXXXXX`
# special case for weird multilib setups
for dir in /lib /lib64 /usr/lib /usr/lib64; do
    test -L $dir && cp -p $dir $tempdir$dir
done

new_target_files=
for i in $target_files; do 
 case $i in
   *=/*)
    target=`echo $i | cut -d= -f1`
    path=`echo $i | cut -d= -f2`
    ;;
   *)
    path=$i
    target=$i
    ;;
  esac
  mkdir -p $tempdir/`dirname $target`
  cp -p $path $tempdir/$target
  if test -f $tempdir/$target -a -x $tempdir/$target; then
    strip -s $tempdir/$target 2>/dev/null
  fi
  target=`echo $target | cut -b2-`
  new_target_files="$new_target_files $target"
done

if test -x /sbin/ldconfig; then
   mkdir -p $tempdir/var/cache/ldconfig
   /sbin/ldconfig -r $tempdir
   new_target_files="$new_target_files etc/ld.so.cache"
fi

md5sum=NONE
for file in /usr/bin/md5sum /bin/md5 /usr/bin/md5 /sbin/md5; do
   if test -x $file; then
	md5sum=$file
        break
   fi
done

# now sort the files in order to make the md5sums independent
# of ordering
target_files=`for i in $new_target_files; do echo $i; done | sort`
md5=`for i in $target_files; do $md5sum $tempdir/$i; done | sed -e 's/ .*$//' | $md5sum | sed -e 's/ .*$//'` || {
  echo "Couldn't compute MD5 sum."
  exit 2
}
echo "creating $md5.tar.gz"
mydir=`pwd`
cd $tempdir
tar -czhf "$mydir/$md5".tar.gz $target_files || {
  echo "Couldn't create archive"
  exit 3
}
cd ..
rm -rf $tempdir
rm -f $tmp_ld_so_conf
